/**
 * Created by apple on 2017/6/8.
 */
var DBFactory = require('../db/mysql_db');
var async = require('async');
var vipDao = module.exports;


//添加vip
vipDao.addVip = function(data,cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    var sql = "select id from app_vip where sid = ? and app_sid = ? limit 1";
    var vaule = [data.sid,data.app_sid];
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            function (callback) {//先查是否存在该vip
                connection.query(sql,vaule,function (err,result) {
                    var id = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, id);
                });
            },

            function (id,callback) {
                if(id) {
                    callback('该vip已存在!',null);
                    return;
                }//到这里说明不存在，则插入
                connection.query('insert into app_vip set ?',[data],function (err,result) {

                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'成功');
                        return;
                    }
                    callback('操作失败',null);
                    console.log('添加vip时操作app_vip表失败');
                });
            },

            function (res,callback) {
                if(!res) {
                    callback('操作失败',null);
                    return;
                }//到这里说明插入app_vip表成功，再去更新下apps表的vip_items字段
                connection.query('update apps set vip_items = vip_items + 1 where sid = ?',[data.app_sid],function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'成功');
                        return;
                    }
                    callback('操作失败',null);
                    console.log('添加vip时操作apps表失败');
                });
            },

            //如果type=2  自动生成一条vip_item记录
            function (res,callback) {
                if(!res) {
                    callback('操作失败',null);
                    return;
                }
                for (var i in data){
                    console.log(i);
                }
                if(data.type == 2) {

                    var itemInfo = {
                        app_sid: data.app_sid,
                        vip_sid: data.sid,
                        lvl: 1,
                        price: 1000,
                        duration: 0,
                        name: '押金',
                        discount: 1.00,
                        status: 1,
                        multi_rate: 1.00,
                        vip_type: 2
                    };
                    connection.query("replace into app_vip_item set ? ", [itemInfo], function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, '操作成功');
                            return;
                        }
                        callback('操作失败', null);
                        console.log('添加vip时操作apps表失败');
                    });
                }else {
                    callback(null, '操作成功');

                }
            }


        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });
}


//添加vip可购项目
vipDao.addVipItem = function(data,cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    var sql = "select type from app_vip where app_sid = ? and sid = ? limit 1";
    var vaule = [data.app_sid,data.vip_sid];
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.query(sql,vaule,function (err,result) {
                    var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, vipInfo);
                });
            },

            function (vipInfo,callback) {
                if(!vipInfo) {
                    callback('该vip不存在!');
                    return;
                }
                if(data.lvl && data.lvl > vipInfo.top_lvl){
                    callback('等级超过上限!');
                    return;
                }
                data.vip_type = vipInfo.type; //服务端加上vip_type
                connection.query('insert into app_vip_item set ?',data,function (err,result) {
                    callback(err,result);
                });

            }

        ],function (err,appInfo) {
            connection.release();
            if(err){
                cb(err);
                return;
            }

            cb(null, appInfo);

        });

    });
}


vipDao.updateVip = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }

    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        var account = data.account;
        var adm_uid = data.adm_uid;
        delete data.account;
        delete data.adm_uid;
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //查要修改参数的原值
            function (callback) {
                connection.query('select * from app_vip where sid = ? and app_sid = ? limit 1',[data.sid,data.app_sid], function (err,result) {
                    var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, vipInfo);
                });
            },

            //修改vip
            function (vipInfo,callback) {
                if(!vipInfo){
                    callback('该vip不存在');
                    return;
                }
                connection.query('update app_vip set ? where sid = ? and app_sid = ?',[data,data.sid,data.app_sid], function (err,result) {
                    if(err){
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,vipInfo);
                        return;
                    }
                    callback('操作失败');
                    console.log('更新vip时修改app_vip表失败');
                });
            },

            //判断是否是修改status，停用vip则一起停用该vip下的可购项目
            function (vipInfo,callback) {
                if(!vipInfo){
                    callback('操作失败');
                    return;
                }

                //修改status为0时，则一起停用该vip下的可购项目，否则直接返回成功
                if (data.status == 0) {
                    connection.query('update app_vip_item set status = 0 where vip_sid = ? and app_sid = ?', [data.sid, data.app_sid], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, vipInfo);
                            return;
                        }
                        callback('操作失败');
                        console.log('更新vip时修改app_vip_item表失败');
                    });
                }else {
                    callback(null,vipInfo);
                }
            },


            //写入admin_log记录
            function (vipInfo,callback) {
                if(!vipInfo) {
                    callback('操作失败');
                    return;
                }


                var logInfo = {
                    adm_uid: adm_uid,
                    account: account,
                    type: 5,
                    app_sid: data.app_sid,
                    detail: 'vip变更：'
                };

                delete data.app_sid;
                delete data.sid;

                for(var p in data){
                    logInfo.detail += p + ':' + vipInfo[p] + '->' + data[p] + ',';
                }
                connection.query('insert into admin_log set ? ',[logInfo],function (err,result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                        return;
                    }
                    callback('操作失败');
                    console.log('更新vip时插入admin_log表失败');
                });

            }

        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}



vipDao.updateVipItem = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        var sql = 'update app_vip_item set ? where id = ?';
        var account = data.account;
        var adm_uid = data.adm_uid;
        delete data.account;
        delete data.adm_uid;
        //为了admin_log表加入记录传进来的accout，adm_uid，保存后删掉
        var value = [data,data.id];
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //查要修改参数的原值
            function (callback) {
                connection.query('select * from app_vip_item where id = ? limit 1',[data.id], function (err,result) {
                    var vipItemInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, vipItemInfo);
                });
            },

            //查要修改的VIP最高等级
            function (vipItemInfo,callback) {
                connection.query('select top_lvl from app_vip where app_sid = ? AND sid = ? limit 1',[vipItemInfo.app_sid,vipItemInfo.vip_sid], function (err,result) {
                    var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                    if(!vipInfo){
                        callback('该vip不存在');
                        return;
                    }
                    if(data.lvl && data.lvl > vipInfo.top_lvl){
                        callback('等级超过上限');
                        return;
                    }
                    callback(err, vipItemInfo);
                });
            },

            //存在则去更新
            function (vipItemInfo,callback) {//更改vip可购项目
                if(!vipItemInfo){
                    callback('该vipItem不存在',null);
                    return;
                }
                connection.query(sql,value,function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,vipItemInfo);
                        return;
                    }
                    callback('操作失败',null);
                    console.log('更改可购项目时插入app_vip_item表失败');
                });
            },

            //更新成功写入admin_log
            function (vipItemInfo,callback) {
                if(!vipItemInfo) {
                    callback('操作失败',null);
                    return;
                }
                var adminInfo = {
                    account: account,
                    adm_uid: adm_uid,
                    type: 5,
                    detail: '可购vip项目变更：'
                };


                delete data.app_sid;
                delete data.vip_sid;
                delete data.lvl;

                //记录修改的参数
                for(var p in data){
                    adminInfo.detail += p + ':' + vipItemInfo[p] + '->' + data[p] + ',';
                }
                connection.query('insert into admin_log set ? ',adminInfo,function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'操作成功');
                        return;
                    }
                    callback('操作失败',null);
                    console.log('更改可购vip项目时操作admin_log表失败')

                });
            }

        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}




vipDao.vipOrItemList = function(data,isVip, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    var sql = isVip == true ? 'select app_sid,sid,top_lvl,name,comment,status,type from app_vip where app_sid = ?' :
        'select id,app_sid,vip_sid,lvl,price,duration,name,discount,status,multi_rate,vip_type from app_vip_item where app_sid = ?';
    var value = [data.app_sid];
    if(data.status){
        sql += ' and status = ? ';
        value.push(data.status);
    }
    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null,result);
        }
    );
}


//设置usuz的vio，默认设置firstVip，有传vip_sid = jihuo设置激活
//firstVip改为精英微淘客，3999的; 精英微淘客可重复设置，激活的权限不可重复设置
//data需要参数： uid，account，app_key，vip_sid（选填）,person_num（选填）
vipDao.setUSUZFirstVip = function (data,cb) {
    if(!data) return cb(new Error(500));
    const newDate = new Date();
    const expireDay  = new Date('2030-08-08');
    const vip_sid = data.vip_sid;
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }

        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //查该用户是否存在该vip
            function (callback) {//更改vip可购项目
                var sql = 'SELECT uid,lvl FROM user_vip WHERE uid = ? AND app_sid = ? AND vip_sid = ? ';
                connection.query(sql,[data.uid,data.app_key,vip_sid],function (err,result) {
                    if(err){
                        callback(err);
                        return;
                    }
                    var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                    if(vipInfo){//设置的激活权限的时候，有权限的就不让设置
                        callback(null,{});
                        return;
                    }
                    callback(null,{lvl:0});
                });
            },

            //设置usuz首推权限
            function (vipInfo,callback) {
                if(isEmptyObj(vipInfo)){
                    return callback(null,{});
                }
                var newVipInfo = {
                    uid: data.uid,
                    account: data.account,
                    app_sid: data.app_key,
                    created_time: newDate,
                    vip_sid: vip_sid,
                    lvl: 0,
                    end_time: expireDay,
                    vip_type: 0,
                };
                var sql = 'REPLACE INTO user_vip SET ? ';
                connection.query(sql,[newVipInfo], function (err,result) {
                    if(err){
                        callback(err);
                        console.log(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,vipInfo);
                    }else {
                        callback('设置失败');
                    }
                });
            },

            //记录vip_log表
            function (vipInfo,callback) {
                if(isEmptyObj(vipInfo)){
                    return callback(null,'设置成功');
                }
                var vipLogInfo = {
                    seller_account: 'srv',
                    client_account: data.account,
                    vip_name: '开通代理附送',
                    vip_type: 0,
                    lvl: 0,
                    duration: 0,
                    cost: 0,
                    vip_expire: expireDay,
                    original_vip_name:'开通代理附送',
                    comment: '开通代理附送',
                    price: 0,
                    num: 1,
                    app_sid: data.app_key,
                    vip_sid: vip_sid,
                };
                var sql = 'INSERT INTO vip_log SET ? ';
                connection.query(sql,[vipLogInfo], function (err,result) {
                    if(err){
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'设置成功');
                    }else {
                        callback('设置失败');
                    }
                });
            }

        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}


vipDao.getIsUSUZVip = function (data,cb) {
    if(!data) return cb(new Error(500));
    var sql = 'SELECT vip_sid,account,uid,end_time';
    sql += ' FROM user_vip WHERE app_sid = ? ';
    var value = [data.app_sid];
    if(data.accounts){
        sql += ' AND account in ? '
        value.push([data.accounts]);
    }else {
        sql += ' AND uid = ? ';
        value.push(data.uid);
    };
    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var res = {};
            var baseVip = {
                jihuo:1,
                firstVip:2
            };
            var userInfoObj_account_key = {};
            var userInfoObj_uid_key = {};
            result.forEach(function (info) {
                var userInfo = userInfoObj_account_key[info.account];
                if (!userInfo) {
                    userInfo = {
                        isVip:false,
                        vip_lvl:0
                    };
                }
                var vip_sid = info.vip_sid;
                if(baseVip[vip_sid]) {
                    userInfo.isVip = true;
                    userInfo.vip_lvl = baseVip[vip_sid];
                }
                userInfoObj_account_key[info.account] = userInfo;
                userInfoObj_uid_key[info.uid] = userInfo;
            });
            if (data.accounts){
                var infos = [];
                for (var key in userInfoObj_account_key) {
                    infos.push(userInfoObj_account_key[key]);
                }
                res.infos = infos;
                cb(null,res);
                return;
            }
            var res = userInfoObj_uid_key[data.uid] ? userInfoObj_uid_key[data.uid] : {isVip:false,vip_lvl:0};
            res.vipInfos = result && result.length > 0 ? result : [];
            cb(null,res);
        }
    );
};

vipDao.userVipList = function (data,cb) {
    var param = {
        par:data,
        findKeys: ['app_sid','vip_sid','account','status'],
        findKeysObj:{
            status:{
                tableName:'ol'
            },
            app_sid:{
                tableName:'ol'
            },
            vip_sid:{
                tableName:'ol',
            },
            account:{
                tableName:'u'
            },
        },
        selectStr: 'ol.*,u.account',
        fromStr: ' order_list ol left join users u on ol.uid = u.uid ',
        DBFactory:DBFactory,
        page:data.page,
        pageSize:data.pageSize,
        startTime:data.startTime,
        endTime:data.endTime,
        timeKey:'created_time',
        orderByObj:{
            orderKey:'created_time',
            orderSort:'desc',
        }
    };
    dbBaseList(param,cb);
};

//设置自定义VIP权限
vipDao.setCustomVip = function(data, cb) {
    var vipInfo = {};
    vipInfo.account = data.account;
    vipInfo.uid = data.uid;
    vipInfo.app_sid = data.app_sid;
    vipInfo.vip_sid = data.vip_sid;
    vipInfo.vip_type = data.vip_type;
    vipInfo.lvl = data.lvl;
    vipInfo.created_time = new Date();
    vipInfo.end_time = data.end_time;
    var sql = 'replace into user_vip set ? ';
    DBFactory.getConnection(function(error, connection) {
        if(error) return cb(error);
        connection.query(sql, vipInfo, function(err) {
            if(err) {
                console.log(err);
                cb(err);
                connection.release();
                return;
            } else {
                setCustomVipLog(data, connection, cb);
            }
        });
    });
}
function setCustomVipLog(data, connection, cb) {
    var sql = 'insert into vip_log set ? ';
    var log = {};
    log.seller_account = data.seller_account ? data.seller_account : 'srv';
    log.client_account = data.account;
    log.vip_name = data.vip_name;
    log.vip_type = data.vip_type;
    log.lvl = data.lvl;
    log.vip_expire = data.end_time;
    log.created_date = new Date();
    log.comment = data.comment;
    log.app_sid = data.app_sid;
    log.vip_sid = data.vip_sid;
    log.sign = data.sign ? data.sign : 0;
    log.cost = data.cost ? data.cost : 0;
    log.duration = data.duration ? data.duration : 0;
    log.price = data.price ? data.price : 0;
    connection.query(sql, log, function(err) {
        if(err) {
            cb(err);
            connection.release();
        } else {
            cb(null, log);
            connection.release();
        }
    });
}